<?php

namespace App\Http\Controllers\Admin;
use App\Model\Demand;
use App\Model\MessageText;
use App\Model\Users;
use App\User;
use App\Model\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class DemandController extends Controller
{
    /**
     * 消息列表
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function dangerlist(Request $quest)
    {
        $type = $quest->input("type",1);
        if($type==1){
            $comName = '应急物资';
            $comNameType = 2;
        }else{
            $comName = '隐患排查';
            $comNameType = 1;
        }
        return view('admin/demand/dangerlist')
            ->with('comName',$comName)
            ->with('comNameType',$comNameType)
            ->with('type',$type);
    }

    /**
     * 导出公共的消息列表
     * @param $request
     * @return array
     */
    public function demandpub($request){
        //获取当前登录者的权限,超级管理显示所有的
        //区管理员 district_admin 区工作人员 district_user 街道管理员 street_admin 街道工作人员 street_user
        $type = $request->input("type",1);
        $role = Auth::guard('admin')->user()->role??'';
        $districta = ['district_admin','district_user'];
        $streeta = ['street_admin','street_user'];
        $district = $street = '';
        $companylist = [];
        //隐患排查
        if($type==1){
            //如果是区管理员或者区工作人员
            if(in_array($role,$districta)) {
                $district = Auth::guard('admin')->user()->district;
                if($district){
                    $companylist = Company::where('district', $district)->select(array('id','comName'))->get()->toArray();
                }
            }
            //如果是街道管理员或者街道工作人员
            if(in_array($role,$streeta)) {
                $street = Auth::guard('admin')->user()->street;
                if($street){
                    $companylist = Company::where('street', $street)->select(array('id','comName'))->get()->toArray();
                }
            }
        }

        //应急物资跟超级管理员
        if(($type==2 && $role == 'emergency') || $role == 'admin') {
            $companylist = Company::select(array('id','comName'))->get()->toArray();
        }
        //获取符合条件的公司id
        $companyIda = array_column($companylist,'id');
        //获取符合条件的公司名称，在列表中会用到公司名称
        $companyName = array_column($companylist,'comName','id');
        //通过公司id获取相关的用户id跟用户与公司关联的id
        $data_user = User::whereIn('companyId',$companyIda)->select(array('id','companyId'))->get()->toArray();
        $userIda = array_column($data_user,'id');
        $userCompany = array_column($data_user,'companyId','id');
        return compact('type','companyName','userIda','userCompany');
    }

    /**
     * 消息数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dangerlistdata(Request $request)
    {
        $pub = $this->demandpub($request);
        $type = $pub['type'];
        $companyName = $pub['companyName'];
        $userIda = $pub['userIda'];
        $userCompany = $pub['userCompany'];
        $query= Demand::whereIn('uid',$userIda)->where('type',$type)->orderby('id','desc');
        $res=$query->paginate($request->get('limit',15))->toArray();
        foreach ($res['data'] as $key=>$val){
            $userCompanyId = isset($userCompany[$val['uid']]) ? $userCompany[$val['uid']] : '';
            $companyTitle = isset($companyName[$userCompanyId]) ? $companyName[$userCompanyId] : '';
            $res['data'][$key]['company_title'] = $companyTitle;
            $res['data'][$key]['time'] = date("Y-m-d H:i:s",$val['time']);;
            $res['data'][$key]['reply_time'] = $val['reply_time'] ? date("Y-m-d H:i:s",$val['reply_time']) : '';
        }
        $data = [
            'code' => 0,
            'msg'   => '请求成功',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * 回复页面
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function replay(Request $request)
    {
        $type = $request->input("type",1);
        $de=Demand::find($request['id']);
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'reply_content' => 'required'
            ],[
                'reply_content.required' => '回复内容必填'
            ]);

            $de->reply_content=$request['reply_content'];
            $de->reply_time=time();
            $de->save();
            //发送消息
            $uid = Auth::guard('admin')->user()->id;
            MessageText::addmessByuid('企业需求上报回复提醒',$de->reply_content,'','',[$de->uid],5,$uid);

            return redirect()->to(route('admin.demand.dangerlist',['type'=>$type]))->with(['status'=>'修改成功']);
        }
        return view('admin/demand/replay')
            ->with('de',$de)
            ->with('type',$type);
    }

    /**
     * 回复页面操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function replaydo(Request $request)
    {
        $user = Auth::guard('admin')->user();
        $data = $request->all();
        $demand=$data;
        $demand['uid']=$user->id;
        $demand['time']=time();
        $id = Demand::insertGetId($demand);
        if($id){
            return response()->json(['message' =>'插入成功','code' => 200], 200);
        }else{
            return response()->json(['message' =>'插入失败','code' => 400], 200);
        }
    }

    /**
     * 导出消息列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportone(Request $request)
    {
        $pub = $this->demandpub($request);
        $type = $pub['type'];
        $companyName = $pub['companyName'];
        $userIda = $pub['userIda'];
        $userCompany = $pub['userCompany'];
        $res= Demand::whereIn('uid',$userIda)->where('type',$type)->orderby('id','desc')->get()->toArray();
        foreach ($res as $key=>$val){
            $userCompanyId = isset($userCompany[$val['uid']]) ? $userCompany[$val['uid']] : '';
            $companyTitle = isset($companyName[$userCompanyId]) ? $companyName[$userCompanyId] : '';
            $res[$key]['company_title'] = $companyTitle;
            $res[$key]['time'] = date("Y-m-d H:i:s",$val['time']);;
            $res[$key]['reply_time'] = $val['reply_time'] ? date("Y-m-d H:i:s",$val['reply_time']) : '';
        }

        if($type==1){
            $comName = '隐患排查';
        }else{
            $comName = '应急物资';
        }

        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load("word/demand.xlsx");
        $objPHPExcel->createSheet();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($comName."消息列表");
        $objActSheet = $objPHPExcel->getActiveSheet();

        $row = 2;
        $i = 1;
        foreach($res as $tt)
        {
            $objPHPExcel->getActiveSheet()->setCellValue("A".$row,$i);
            $objPHPExcel->getActiveSheet()->setCellValue("B".$row,$tt['company_title']);
            $objPHPExcel->getActiveSheet()->setCellValue("C".$row,$tt['title']);
            $objPHPExcel->getActiveSheet()->setCellValue("D".$row,$tt['content']);
            $objPHPExcel->getActiveSheet()->setCellValue("E".$row,$tt['reply_content']);
            $objPHPExcel->getActiveSheet()->setCellValue("F".$row,$tt['time']);
            $objPHPExcel->getActiveSheet()->setCellValue("G".$row,$tt['reply_time']);
            $row++;
            $i++;
        }
        for ($x=1; $x<=($row); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度
        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:E'.($row+10))->applyFromArray($styleArray);//设置粗边框
        $objActSheet->getRowDimension(1)->setRowHeight(30);//单独设置行高度
        $write = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename='.$comName.'消息列表.xls');//可以让浏览器弹出下载窗口
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
        exit();
    }
}
